package my.springboot.validation.verify;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import my.util.JsonUtil;

import org.apache.log4j.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 * @author xsw
 * @date 2018-6-5
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	
	private Logger log = Logger.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 参数校验异常处理
	 * @param request
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value=MethodArgumentNotValidException.class)
	public Object beanValidation(HttpServletRequest request,MethodArgumentNotValidException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		FieldError fieldError = fieldErrors.get(0);
		log.debug("【错误结果】"+fieldError.getDefaultMessage());
		return null;
	}
	
	@ExceptionHandler(value=HttpMessageNotReadableException.class)
	public Object beanValidation(HttpServletRequest request,HttpMessageNotReadableException exception) {
		Throwable mostSpecificCause = exception.getMostSpecificCause();
		String objToJson = JsonUtil.objToJson(mostSpecificCause);
		String detailMessage = JsonUtil.getJsonNodeValue(objToJson, "originalMessage");
		log.debug("【错误结果】"+detailMessage);
		return null;
	}
}
